﻿using System;
using System.Data;
using System.Net;
using System.Text;
using System.IO;
using System.Drawing;

namespace PolePosition.v3.WcfService
{
    public partial class GetImage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["TYPE"] != null && Request.QueryString["ID"] != null && 
                Request.QueryString["HEIGHT"] != null && Request.QueryString["WIDTH"] != null)
            {
                System.Data.SqlClient.SqlCommand _SqlCommand;
                _SqlCommand = new System.Data.SqlClient.SqlCommand();

                _SqlCommand.CommandText = GetSPNameByType(Request.QueryString["TYPE"]);
                _SqlCommand.Parameters.AddWithValue("@imageID", Request.QueryString["ID"]);

                DataSet dsImage = ProjectCommon2.Helpers.SqlHelper.ExecuteDataSet(_SqlCommand);

                if (dsImage.Tables.Count > 0)
                {
                    string imageUrl = GetFilePath(Request.QueryString["TYPE"], dsImage.Tables[0].Rows[0]);
                    int height = Convert.ToInt32(Request.QueryString["HEIGHT"]);
                    int width = Convert.ToInt32(Request.QueryString["WIDTH"]);

                    ShowImage(imageUrl, height, width);
                }
            }
        }

        void ShowImage(string url, int height, int width)
        {
            // argument passed?
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException("url");
            if (width < 1)
                throw new ArgumentOutOfRangeException("width");
            if (height < 1)
                throw new ArgumentOutOfRangeException("height");

            // does the file exist?
            //if (!System.IO.File.Exists(path))
            //    throw new System.IO.FileNotFoundException(path);

            // load image
            var _Brownser = new WebClient();
            byte[] imageBuffer = _Brownser.DownloadData(url);
            var mStream = new MemoryStream(imageBuffer, 0, imageBuffer.Length);

            if (imageBuffer.Length > 0)
            {
                using (Bitmap _Bitmap = new Bitmap(mStream))
                {
                    // resize image

                    using (
                        Bitmap _ResizedBitmap = new Bitmap(width, height,
                                                           System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                    {
                        // draw new image

                        using (Graphics _Surface = Graphics.FromImage(_ResizedBitmap))
                        {
                            _Surface.InterpolationMode =
                                System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            _Surface.DrawImage(_Bitmap, 0, 0, width, height);
                            _Surface.Dispose();
                        }

                        // move to byte[]

                        byte[] _Bytes;
                        using (MemoryStream _MemoryStream = new MemoryStream())
                        {
                            _ResizedBitmap.Save(_MemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                            _Bytes = _MemoryStream.ToArray();
                        }

                        // output to page

                        Response.Expires = 0;
                        Response.Buffer = true;
                        Response.Clear();
                        Response.ContentType = "image/jpeg";
                        Response.BinaryWrite(_Bytes);
                        Response.End();
                    }
                }
            }
        }

        private static string GetSPNameByType(string type)
        {
            switch (type)
            {
                case "AssetDistribution":
                    return "up_Utility_Asset_Distributions_Images_SelectById";
                case "AssetXmission":
                    return "up_Utility_Asset_XMissionStructures_Images_SelectById";
                case "InspectionPoleDistribution":
                    return "up_Vendor_Visit_Distributions_Images_SelectById";
                case "InspectionPoleXmission"	:
                    return "up_Vendor_InspVisit_XMissionStructures_Images_SelectById";
                case "GPSPoleDistribution":
                    return "up_Vendor_Visit_Distributions_Images_SelectById";
                case "GPSPoleXmission":
                    return "up_Vendor_Visit_XMissionStructures_Images_SelectById";
                case "InspectionMeterDistribution":
                    return "up_Vendor_Visit_Distributions_MeterImages_SelectById";
                case "MeterAssetDistribution":
                    return "up_Utility_Asset_Distributions_MeterImages_SelectById";
                case "InspectionTransformerDistribution":
                    return "up_Vendor_Visit_Distributions_TransformerImages_SelectById";
                case "TransformerAssetDistribution":
                    return "up_Utility_Asset_Distributions_TransformerImages_SelectById";
                case "InspectionSectionalizerDistribution":
                    return "up_Vendor_Visit_Distributions_SectionalizerImages_SelectById";
                case "InspectionRecloserDistribution":
                    return "up_Vendor_Visit_Distributions_RecloserImages_SelectById";
            }

            return string.Empty;
        }

        private static string GetFolderNameByType(string type)
        {
            switch (type)
            {
                case "AssetDistribution":
                    return "DistributionGPS";
                case "AssetXmission":
                    return "Utility_Asset_XMissionStructures";
                case "InspectionPoleDistribution":
                    return "DistributionInspection";
                case "InspectionPoleXmission":
                    return "Inspection";
                case "GPSPoleDistribution":
                    return "DistributionGPS";
                case "GPSPoleXmission":
                    return "GPS";
                case "InspectionMeterDistribution":
                case "MeterAssetDistribution":
                    return "DistributionInspectionMeterImages";
                case "InspectionTransformerDistribution":
                case "TransformerAssetDistribution":
                    return "DistributionInspectionTransformerImages";
                case "InspectionSectionalizerDistribution":
                    return "DistributionInspectionSectionalizerImages";
                case "InspectionRecloserDistribution":
                    return "DistributionInspectionRecloserImages";
            }

            return string.Empty;
        }

        private string GetFilePath(string type, DataRow drImage)
        {
            //up_Settings_SelectAllByKey 'BaseImageStorageUrl'

            //Get base Url for images
            System.Data.SqlClient.SqlCommand _SqlCommand;
            _SqlCommand = new System.Data.SqlClient.SqlCommand();
            _SqlCommand.CommandText = "up_Settings_SelectAllByKey";
            _SqlCommand.Parameters.AddWithValue("@key", "BaseImageStorageUrl");

            DataTable tbSettings = ProjectCommon2.Helpers.SqlHelper.ExecuteDataTable(_SqlCommand);
            string baseUrl = string.Empty;
            if (tbSettings.Rows.Count > 0)
                baseUrl = tbSettings.Rows[0]["SettingValue"].ToString();

            //Build complete path
            StringBuilder completePath = new StringBuilder(baseUrl);
            completePath = completePath.Append(GetFolderNameByType(type)).Append(@"/");

            if (drImage["ID"] != DBNull.Value && drImage["FileName"] != DBNull.Value)
                completePath = completePath.Append(GetDirectoryName((int)drImage["PoleId"])).Append(@"/").Append(drImage["FileName"]);

            return completePath.ToString();
        }

        //TODO: Move to common library
        private string GetDirectoryName(int parentId)
        {
            //copied from old PPI client
            int Start = 0;
            int End = 99;
            string _Directory = "";
            bool _FoundPosition = false;
            while (!_FoundPosition)
            {
                if (parentId > Start && parentId > End)
                {
                    Start += 100;
                    End += 100;
                }
                else
                {
                    _FoundPosition = true;
                    _Directory = Start + "-" + End;
                }
            }
            return _Directory;
        }
    }
}
